package com.haojin.java2;

import com.haojin.java1.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author .29.
 * @create 2022-04-19 16:21
 */
/*
获取运行时类的方法结构
 */
public class MethodTest {
    @Test
    public void test(){
        Class<Person> personClass = Person.class;
        //getMethods():获取当前运行时类及其所有类中声明的public权限方法
        Method[] methods = personClass.getMethods();
        for (Method m :
                methods) {
            System.out.println(m);
        }

        System.out.println();
        //getDeclaredMethods()：获取当前运行时类中声明的所有方法，不包含父类中声明的方法
        Method[] declaredMethods = personClass.getDeclaredMethods();
        for (Method m1 :
                declaredMethods) {
            System.out.println(m1);
        }

    }

    /*
    权限修饰符  返回值类型  方法名（参数类型）throws XxxExceptions{}
     */
    @Test
    public void test2(){
        Class<Person> personClass = Person.class;
        Method[] methods = personClass.getMethods();
        for (Method m :
                methods) {
            //1.获取方法声明的注解
            Annotation[] declaredAnnotations = m.getDeclaredAnnotations();
            for (Annotation a :
                    declaredAnnotations) {
                System.out.println(a);
            }
            //2.权限修饰符
            System.out.print(Modifier.toString(m.getModifiers()) + "\t");

            //3.返回值类型
            System.out.print(m.getReturnType().getName() + "\t");

            //4.方法名
            System.out.print(m.getName());
            System.out.print("(");
            //5.形参列表
            Class<?>[] parameterTypes = m.getParameterTypes();
            if (!(parameterTypes == null && parameterTypes.length == 0)){
                for (int i = 0; i < parameterTypes.length; i++){
                    if (i == parameterTypes.length-1){
                        System.out.print(parameterTypes[i].getName()+"args_"+i);
                    }else{
                        System.out.print(parameterTypes[i].getName()+"args_"+i+",");
                    }
                }
                System.out.print(")");
            }else{
                System.out.print(")");
            }
            //6.抛出的异常
            Class<?>[] exceptionTypes = m.getExceptionTypes();
            if (exceptionTypes.length > 0) {
                System.out.print("throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length - 1) {
                        System.out.print(exceptionTypes[i] + "args_" + i);
                    } else {
                        System.out.print(exceptionTypes[i] + "args_" + i + ",");
                    }
                }
            }
            System.out.println();
        }
    }
}
